package cmds

import (
	"fmt"
	"generate-iot-cmd/internal/model"
	"generate-iot-cmd/internal/utils"
	"log"
)

func initCmds(iotCmd model.CmdModel) (commands []string) {
	commands = make([]string, 0)
	for _, addressModel := range iotCmd.AddressModel {
		for _, cmd := range addressModel.Cmds {
			cmdWithout0x, err := utils.GenerateWithLittleEndianCRC16(addressModel.Address + cmd)
			if err != nil {
				log.Fatalf("Error generating CRC16, %s", err)
			}
			cmdWith0x := utils.CmdAdd0x(cmdWithout0x)
			commands = append(commands, cmdWith0x)
		}
	}
	return commands
}

func generateCmds(c *CMDService) (result string) {
	for idx, cmd := range c.Commands {
		result += fmt.Sprintf("cmd_%02d=%s\n", idx+1, cmd)
	}
	result += "num=0\n"
	return
}

func generateUartReceiver(c *CMDService) (result string) {

	/*** beta, 还需要实际测试一下 ***
	dataall=[]
	pre_data=[]
	data=[]
	pre_address=[0x01]
	RECV UART uart
	        data=INPUT
		# 需要看下汉枫脚本和以前的脚本看下如何判断地址
		now_address=[]
		IF(now_address==pre_address)
			dataall=dataall+data
		ELSE
			IF(dataall.length()>0)
				SEND(SOCK,B,dataall)
				dataall=[]
			ELSE
				SEND(SOCK,B,pre_data)
			END
		END
		pre_address=now_address
		pre_data=data
		data=[]
	END
	**/

	// 暂时先只生成最简单的接收处理逻辑
	result += "data=[]\n"
	result += "dataall=[]\n"
	result += "RECV UART uart\n"

	// todo: generate receiver handler
	result += "	data=INPUT\n"

	result += "	SEND(SOCK,B,data)\n"

	result += "	data=[]\n"
	result += "END\n"
	return
}

func generateSendCmds(c *CMDService) (result string) {
	result = "TIMER Polling " + fmt.Sprintf("%d", c.IOTCmdModel.Interval) + "\n"
	result += "	num=num+1\n"

	for idx := range c.Commands {
		result += fmt.Sprintf("	IF(num==%d)\n", idx+1)
		result += fmt.Sprintf("		SEND(UART,uart,cmd_%02d)\n", idx+1)
		result += "	END\n"
	}

	result += fmt.Sprintf("	IF(num==%d)\n", c.IOTCmdModel.MaxCount)
	result += "		num=0\n"
	result += "	END\n"
	result += "END"
	return
}
